package com.truyensex.ui;

import info.androidhive.slidingmenu.R;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.truyensex.dao.truyenManager;
import com.truyensex.model.Article;

public class HomeFragment extends Fragment {
	ProgressBar progressbar;
	Button btnTaiLai;
	Thread threadnetwork = null;
	private AdView adView;
	TextView a;
	public HomeFragment()
	{
		Log.i("Home","khoi tao");
	}
	/*@Override
	public void onSaveInstanceState(Bundle outState) {
		Log.i("SAVE","save");
		super.onSaveInstanceState(outState);
		Calendar c = Calendar.getInstance();
		Date date = c.getTime();
		for(int i=0;i<5;i++)
		{
			Article a = new Article(i,"i: "+i, "aaa",date, "QuangDIEN", false);
			truyenManager.listArticle.add(a);
		}
		Log.i("SAVE","size" + truyenManager.listArticle.size());
		outState.putSerializable("list", truyenManager.listArticle);
	}*/
	@SuppressWarnings("unchecked")
	@SuppressLint("ShowToast")
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        //progressbar =  (ProgressBar) rootView.findViewById(R.id.progressBar1);
        btnTaiLai = (Button) rootView.findViewById(R.id.button1);

        if(truyenManager.firstLoading==true)
        {
        	truyenManager.firstLoading = false;
        	initData();
        }
        /*if(truyenManager.firstLoading==true)
        {
        	truyenManager.firstLoading =false;
        	loadingData();
        }else
        {
        	Log.i("Home", "2" + "update ui");
        	getActivity().getActionBar().setHomeButtonEnabled(true);
        	progressbar.setVisibility(View.GONE);
        }*/
        btnTaiLai.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//loadingData();
				initData();
			}
		});
        return rootView;
    }
	@SuppressLint("NewApi")
	public void initData()
	{
		if(checkOnlineState()==true)
        {
			loadingDataFromInternet();
        	//Toast.makeText(getActivity(), "Có internet", Toast.LENGTH_LONG);
        	btnTaiLai.setVisibility(View.GONE);
        	Fragment fragment = new ListArticleFragment();
			if (fragment != null) {
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.frame_container, fragment).addToBackStack(null).commit();
			} else 
			{
				Log.e("MainActivity", "Error in creating fragment");
			}
			getActivity().getActionBar().setHomeButtonEnabled(true);
        }
        else
        {
        	//Toast.makeText(getActivity(), "", Toast.LENGTH_LONG);
        	AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	        builder.setMessage("Vui lòng kết nối internet")
	               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	                   public void onClick(DialogInterface dialog, int id) {
	                   }
	               });
	        builder.create().show();
        	btnTaiLai.setVisibility(View.VISIBLE);
        	getActivity().getActionBar().setHomeButtonEnabled(false);
        }
	}
	/*@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}*/
	/*@Override
	public void onViewStateRestored(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewStateRestored(savedInstanceState);
		Toast.makeText(getActivity(), "onViewStateRestored", Toast.LENGTH_LONG).show();
	}*/
	@Override
	public void onResume() {
		super.onResume();
		//Toast.makeText(getActivity(), "onResume", Toast.LENGTH_LONG).show();
		/*Log.i("Home", "onResume");
		truyenManager.isStoped = false;
		if(truyenManager.isLoading==false)
		{
			progressbar.setVisibility(View.GONE);
			getActivity().getActionBar().setHomeButtonEnabled(true);
		}*/
	}
	@Override
	public void onPause() {
		super.onPause();
		/*truyenManager.isStoped = true;
		if(threadnetwork!=null)
		{
			threadnetwork.interrupt();
		}
		Log.e("Home", "onCreateView");*/
	}
	@Override
	public void onStop() {
		super.onStop();
		//Toast.makeText(getActivity(), "Stopped", Toast.LENGTH_LONG).show();
		Log.e("Home", "Stopped");
	}
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		//Toast.makeText(getActivity(), "OnDestroyview", Toast.LENGTH_LONG).show();
		
		Log.e("Home", "OnDestroyview");
	}
	@Override
	public void onDetach() {
		super.onDetach();
		//Toast.makeText(getActivity(), "onDetach", Toast.LENGTH_LONG).show();
		Log.e("Home", "onDetach");
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		//Toast.makeText(getActivity(), "Destroy", Toast.LENGTH_LONG).show();
		Log.e("Home", "onDestroy");
	}
	public boolean checkOnlineState() {
	    ConnectivityManager CManager =
	        (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
	    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
	
	public void loadingDataFromInternet()
	{
		
		try
		{
			InputStream is = getActivity().getAssets().open("test.xml");
			truyenManager.readListArticleFromFile(is);
			/*XmlOperation xmlFromFile = new XmlOperationFromFile(is);
			xmlFromFile.readXml();
			truyenManager.listArticle =(ArrayList<Article>) xmlFromFile.getListObject();*/
		}catch(IOException ex)
		{
			Log.e("exp", ex.getMessage());
		}
	}
/*	public void loading()
	{
		if(truyenManager.statusLoading==false)
        {
	        getActivity().getActionBar().setHomeButtonEnabled(false);
	        progressbar.setVisibility(View.VISIBLE);
	        loadingData();
	        truyenManager.statusLoading = true;
	        Toast.makeText(getActivity(), "Loading xong du lieu", Toast.LENGTH_LONG);
        }
        progressbar.setVisibility(View.GONE);
        getActivity().getActionBar().setHomeButtonEnabled(true);
	}*/
	/*public void loadingData()
	{
		progressbar.setVisibility(View.VISIBLE);
		Log.i("Home", "start loading");
		getActivity().getActionBar().setHomeButtonEnabled(false);
		threadnetwork = new Thread()
			{
				@Override
				public void run() {
					if(checkOnlineState()==false)
					{
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								progressbar.setVisibility(View.GONE);
								btnTaiLai.setVisibility(View.VISIBLE);
								Toast.makeText(getActivity(), "Vui long kiêm tra lại mạng", Toast.LENGTH_LONG).show();
								getActivity().getActionBar().setHomeButtonEnabled(false);
							}
						});
						this.interrupt();
						return;
					}
					else
					{
							truyenManager.readListArticleFromInternet("http://newblobdemo.blob.core.windows.net/mycontainer/vxml2");
							Log.i("Home", "finish loading");
							Log.i("Home", "updatUI after loading");
							if(truyenManager.isBack==true)
							{
								truyenManager.isBack = false;
								Log.i("Home", "Thoat thread");
								this.interrupt();
								return;
							}
							truyenManager.isLoading = false;
							if(truyenManager.isStoped==false)
							{
								Log.i("Home", "update ui");
								getActivity().runOnUiThread(new Runnable() {
									@Override
									public void run() {
										progressbar.setVisibility(View.GONE);
										Fragment fragment = new ListArticleFragment();
										if (fragment != null) {
											FragmentManager fragmentManager = getFragmentManager();
											fragmentManager.beginTransaction()
													.replace(R.id.frame_container, fragment).addToBackStack(null).commit();
										} else 
										{
											Log.e("MainActivity", "Error in creating fragment");
										}
										getActivity().getActionBar().setHomeButtonEnabled(true);
										
									}
								});
							}
					}
				}
			};
			threadnetwork.start();
	}*/
	
	
}
